from django.shortcuts import render,HttpResponse,redirect
from datetime import datetime
from django.urls import reverse
import re
import json
from django.core.mail import send_mail
from django.core.mail import EmailMultiAlternatives
from django.conf import settings

from .models import Article,Category,Category2,Web,Vip, History, Collection, Banner,Ad, Page
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage, InvalidPage
from django.contrib import messages
from django.db.models import Q
from itertools import chain
from django.http import JsonResponse

from apps.Userinfo.views import RegisterView

class index:
    ## get Category list by select web in page
    def page(request,link):
        page = Page.objects.filter(link=link).first()


        pages = Page.objects.all().order_by('index')
        page_list = [{'link': i.link, 'name': i.name} for i in pages]


        return render(request, 'page.html',{
            'title': page.name,
            'body': page.body,
            'page_list': page_list
        })
    def getCategory(request):
        if request.method == 'GET':
            web = request.GET.get('id')
            if web:
                data = list(Category.objects.filter(web_id=web).order_by('index').values("name", "id"))
                return JsonResponse(data, safe=False)

    ## get Category2 list by select Category in page
    def getCategory2(request):
        if request.method == 'GET':
            category = request.GET.get('id')
            if category:
                data = list(Category2.objects.filter(category_id=category).values("name", "id"))
                return JsonResponse(data, safe=False)
    def get(request, web=None,category=None,category2=None, tags=None):
        web = request.GET.get('web')
        category = request.GET.get('category')
        category2 = request.GET.get('category2')

        pages = Page.objects.all().order_by('index')
        page_list = [{'link': i.link, 'name': i.name} for i in pages]

        # 首页
        if not web and not category and not category2:
            news = Article.objects.filter(web__name='NEWS・政策').order_by('-created_time')
            # menu菜单-子网站
            webs = Web.objects.all()
            articles_1 = Article.objects.filter(web__name='NEWS・政策').order_by('-created_time')[:10]
            articles_2 = Article.objects.filter(web__name='有機原料').order_by('-created_time')[:10]
            articles_3 = Article.objects.filter(web__name='フッ素工業').order_by('-created_time')[:10]
            articles_4 = Article.objects.filter(web__name='無機原料').order_by('-created_time')[:10]
            articles_5 = Article.objects.filter(web__name='農薬').order_by('-created_time')[:10]
            articles_6 = Article.objects.filter(web__name='臭素工業').order_by('-created_time')[:10]
            articles_7 = Article.objects.filter(web__name='肥料').order_by('-created_time')[:10]
            articles_8 = Article.objects.filter(web__name='リン工業').order_by('-created_time')[:10]

            ads = Banner.objects.filter(zone='0', is_active=True)

            return render(request, 'index2.html', locals())

        # 子网站
        if web and not category and not category2:
            articles = Article.objects.filter(web__name=web).order_by('-created_time')

        # 子网站-分类
        if category and not category2:
            #strlist = category.split(' --- ')
            #category = strlist[1]
            if not web:
                try:
                    # aaa = Category.objects.get(name=category)
                    # web = Category.objects.get(name=category).web.name
                    articles = Article.objects.filter(web__name=web, category__name=category).order_by('-created_time')
                except:
                    web = Category.objects.filter(name=category).first().web.name
                    articles = Article.objects.filter(web__name=web, category__name=category).order_by('-created_time')
            else:
                articles = Article.objects.filter(web__name=web, category__name=category).order_by('-created_time')



        # 子网站-分类-子分类
        if category2:
            if not category:
                try:
                    c = Category2.objects.filter(name=category2)
                    # category = Category2.objects.get(name=category2).category.name
                except:
                    category = None
            else:
                articles = Article.objects.filter(category__name=category, category2__name=category2).order_by(
                    '-created_time')

            if not web:
                try:
                    web = Category.objects.get(name=category).web.name
                    articles = Article.objects.filter(web__name=web, category__name=category, category2__name=category2).order_by('-created_time')
                except:
                    articles = Article.objects.filter(category__name=category, category2__name=category2).order_by('-created_time')
            else:
                articles = Article.objects.filter(web__name=web, category__name=category, category2__name=category2).order_by('-created_time')



        paginator = Paginator(articles, 20)
        page = request.GET.get('page')
        try:
            articles = paginator.page(page)
            # todo: 注意捕获异常
        except PageNotAnInteger:
            # 如果请求的页数不是整数, 返回第一页。
            articles = paginator.page(1)
        except InvalidPage:
            # 如果请求的页数不存在, 重定向页面
            return HttpResponse('ページが見つかりません')
        except EmptyPage:
            # 如果请求的页数不在合法的页数范围内，返回结果的最后一页。
            articles = paginator.page(paginator.num_pages)

        #ads = Banner.objects.filter(zone='1', is_active=True)
        ads = Ad.objects.all().order_by('id')

        return render(request, 'list_wenzhang.html', {'articles': articles,
                                                      'web': web,
                                                      'category': category,
                                                      'category2': category2,
                                                      'ads': ads,
                                                      'page_list':page_list})

    def search(request):
        word = request.GET.get('q').split()
        if word:
            articles = Article.objects.filter(Q(title__icontains=word[0]) | Q(body__icontains=word[0])).order_by('-created_time')

        else:
            return redirect(reverse('index'))

        # articles = chain.from_iterable(articles)
        paginator = Paginator(articles, 20)

        page = request.GET.get('page')
        try:
            articles = paginator.page(page)
            # todo: 注意捕获异常
        except PageNotAnInteger:
            # 如果请求的页数不是整数, 返回第一页。
            articles = paginator.page(1)
        except InvalidPage:
            # 如果请求的页数不存在, 重定向页面
            return HttpResponse('ページが見つかりません')
        except EmptyPage:
            # 如果请求的页数不在合法的页数范围内，返回结果的最后一页。
            articles = paginator.page(paginator.num_pages)

        ads = Ad.objects.all().order_by('id')

        pages = Page.objects.all().order_by('index')
        page_list = [{'link': i.link, 'name': i.name} for i in pages]
        return render(request, 'list_search.html', {'articles': articles,
                                                      'q': word[0],
                                                      # 'category': category,
                                                      # 'category2': category2
                                                      'ads': ads,
                                                    'page_list':page_list})


class article:
    def article_list(request, web=None,category=None,category2=None, tags=None):
        ads = Ad.objects.filter(is_active=True).order_by('id')
        articles = Article.objects.all()[:10]

        paginator = Paginator(articles, 3, 1)
        pages = Page.objects.all().order_by('index')
        page_list = [{'link': i.link, 'name': i.name} for i in pages]
        return render(request, 'list_wenzhang.html',{'articles':articles,
                                                     'page_list':page_list,
                                                        'ads': ads,})

    def article_details(request, id):
        ads = Ad.objects.filter(is_active=True).order_by('id')
        article = Article.objects.get(id=id)
        web = article.web.name if article.web else None
        category = article.category.name if article.category else None
        category2 = article.category2.name if article.category2 else None
        level = article.level.name if article.level else None

        pages = Page.objects.all().order_by('index')
        page_list = [{'link': i.link, 'name': i.name} for i in pages]


        if level == '登录用户可看' and not request.user.is_authenticated:
            messages.error(request, "この文章は登録者のみ見えます，登録してください。")
            return redirect('/login')
        elif level == 'VIP用户可看':
            if not request.user.is_authenticated:
                messages.error(request, "この文章はVIP登録者のみ見えます，登録してください。")
                return redirect('/login')
            else:
                now = datetime.now()
                vip_all = Vip.objects.filter(user=request.user,web=0,start_time__lte=now,end_time__gte=now)
                vip = Vip.objects.filter(user=request.user,web=article.web,start_time__lte=now,end_time__gte=now)

                if not vip_all and not vip:
                    messages.error(request, "この文章はVIP登録者のみ見えます，VIPプランを買ってください。")
                    return redirect('/uc-account')

        # 更新浏览历史
        if request.user.is_authenticated:
            new_est = History.objects.filter(user=request.user).last()
            if new_est and new_est.article == article:
                new_est.created_time = datetime.now()
                new_est.save()
            else:
                h = History(user=request.user, article=article)
                History.save(h)

        # 更新访问量
        article_count = article.views
        article_count += 1
        article.views = article_count
        article.save()

        # 收藏
        if request.user.is_authenticated:
            co = Collection.objects.filter(user=request.user, article=article)
        else:
            co = None
        return render(request, 'onepage.html',{'article':article,
                                               'web': web,
                                               'co': co,
                                                'ads': ads,
                                               'page_list':page_list})